package com.kdtech.analyse.video;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.analyse.AnalyseNews;

public class BaojizxAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		//http://www.baojizx.com/video/2011-07/11/cms22891article.shtml
//		http://www.baojizx.com/news/2014-08/15/cms64237article.shtml
		String[] regex = { "http://www.baojizx.com/(video|news)/[0-9]{4}-[0-9]{2}/[0-9]{2}/cms[0-9]*article.shtml",
				"http://www.baojizx.com/[a-z0-9\\/\\-]+/cms[0-9]+article.shtml"
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (!isDetailPage(urlMeta.getUrl())) {
		}
		NewsMeta video = new NewsMeta();
		if (urlMeta.getHtml() == null) {
			return null;
		}
		String html = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		video.setUrl(url);
		String title = null;
		String desc = null;
		Long date = 0l;

		Document doc = Jsoup.parse(html);
		/*
		 * 解析标题
		 */
		title= doc.select("div.nrq_title").text();
		/*
		 * 解析时间
		 */
		String text = doc.select("div.nrq_ly").text();
		date = DateUtils.matchDate(text);

		if (StringUtils.isBlank(title)) {
		}
		desc =HtmlCleaner.getContentHtml(url, doc.select("div#cms_content_div"));
		video.setContent(desc);
		video.setTitle(title);
		video.setDate(date);
		return video;
	}

	private final static Pattern P_PATH = Pattern
			.compile("[0-9]{4}/[0-9]{2}/[0-9]{4}-[0-9]{2}-[0-9]*.html");

	
	public NewsMeta Update(NewsMeta meta) {

		
		return null;
	}

	public static void main(String[] args) {
		BaojizxAnalyse a = new BaojizxAnalyse();
		String url = "http://www.baojizx.com/xqdt/2015-10/19/cms75789article.shtml";
		if (a.isDetailPage(url)) {
			UrlMeta meta = CrawlHTML.responseToURL(url);
			NewsMeta parserHtml = a.parserHtml(meta);
			System.out.println(parserHtml);
		} else {
			System.out.println("不匹配规则");
		}

	}

	
}
